<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from '../mixins/resize'

  const animationDuration = 1000

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '100%'
      },
      chartData: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el)
        this.setOption(this.chartData)
      },
      setOption({data,offset}={}){
        this.chart.setOption({
          color:['#67C23A','#409EFF','#F56C6C','#E6A23C'],
          title: {
            text: (offset==1?'今日':'最近7天')+'故障车型占比',
            subtext: '',
            left:'center',
            bottom: 30
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '30'
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: data,
              label:{
                formatter:'{b}: {d}%'
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
        if(data.length<=0){
          this.chart.showLoading({
            text:(offset==1?'今日':'最近7天')+'暂无生产数据',
            fontSize: 14,
            showSpinner:false
          })
        }else{
          this.chart.hideLoading()
        }
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.chart.hideLoading()
          this.setOption(val)
        }
      }
    },
  }
</script>
